var express = require('express');
var router = express.Router();

// 导入医美模块模型
const { userModel, productModel, hospitalModel, doctorModel, bannerModel } = require('../db/models/cosmetic');
const { ProductCategoryModel } = require('../db/product_category');
const { ProductTypeModel } = require('../db/producttype');
const { processImageURL } = require('../utils/getNetworkIP');

// ========== 轮播图接口 ==========
// 获取轮播图列表
router.get('/banners', async (req, res) => {
  try {
    const { city, province } = req.query;
    let query = { isActive: true };
    
    // 如果指定了地区，则筛选该地区的轮播图，否则获取全国通用的
    if (city && province) {
      query.$or = [
        { city: city, province: province },
        { city: null, province: null } // 全国通用的
      ];
    }
    
    const banners = await bannerModel.find(query).sort({ sort: 1, createTime: -1 });
    res.send({
      success: true,
      data: banners
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取轮播图失败',
      error: error.message
    });
  }
});

// ========== 商品接口 ==========
// 获取商品列表
router.get('/products', async (req, res) => {
  try {
    const { category, city, province, page, limit } = req.query;
    let query = {};
    
    // 分类筛选 - 需要先根据分类名称查找对应的ObjectId
    if (category) {
      // 从product_category集合查找分类ID
      const categoryDoc = await ProductCategoryModel.findOne({ name: category });
      if (categoryDoc) {
        query.category = categoryDoc._id;
      } else {
        // 如果找不到分类，返回空结果
        return res.send({
          success: true,
          data: [],
          pagination: page && limit ? {
            page: parseInt(page) || 1,
            limit: parseInt(limit) || 10,
            total: 0,
            pages: 0
          } : undefined
        });
      }
    }
    
    // 地区筛选
    if (city && province) {
      query.city = city;
      query.province = province;
    }
    
    // 如果没有指定分页参数，返回所有数据
    if (!page && !limit) {
      const products = await productModel.find(query)
        .populate('category', 'name') // 填充分类信息
        .sort({ isHot: -1, viewCount: -1, createTime: -1 });
      
      // 处理图片URL - 使用自动获取的网络IP
      const processedProducts = products.map(product => ({
        ...product.toObject(),
        image: processImageURL(product.image, '3000')
      }));
      
      res.send({
        success: true,
        data: processedProducts
      });
    } else {
      // 分页查询
      const pageNum = parseInt(page) || 1;
      const limitNum = parseInt(limit) || 10;
      const skip = (pageNum - 1) * limitNum;
      
      const products = await productModel.find(query)
        .populate('category', 'name') // 填充分类信息
        .sort({ isHot: -1, viewCount: -1, createTime: -1 })
        .skip(skip)
        .limit(limitNum);
      
      const total = await productModel.countDocuments(query);
      
      // 处理图片URL - 使用自动获取的网络IP
      const processedProducts = products.map(product => ({
        ...product.toObject(),
        image: processImageURL(product.image, '3000')
      }));
      
      res.send({
        success: true,
        data: processedProducts,
        pagination: {
          page: pageNum,
          limit: limitNum,
          total,
          pages: Math.ceil(total / limitNum)
        }
      });
    }
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取商品列表失败',
      error: error.message
    });
  }
});

  // 获取商品分类
  router.get('/products/categories', async (req, res) => {
    try {
      // 从product_category集合获取分类数据
      const categories = await ProductCategoryModel.find({})
        .select('name')
        .sort({ createTime: 1 });
      
      if (categories.length === 0) {
        return res.send({
          success: true,
          data: ['热门', '补水保湿', '瘦脸', '去黑眼圈', '塑形']
        });
      }
      
      // 提取分类名称
      const categoryNames = categories.map(cat => cat.name).filter(name => name && name.trim() !== '');
      const finalCategories = categoryNames.length > 0 ? categoryNames : ['热门'];
      
      res.send({
        success: true,
        data: finalCategories
      });
    } catch (error) {
      console.error('获取商品分类失败:', error);
      res.status(500).send({
        success: false,
        message: '获取商品分类失败',
        error: error.message
      });
    }
  });

// 获取商品详情
router.get('/products/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const product = await productModel.findById(id)
      .populate('category', 'name'); // 填充分类信息
    
    if (!product) {
      return res.status(404).send({
        success: false,
        message: '商品不存在'
      });
    }
    
    // 增加浏览次数
    await productModel.findByIdAndUpdate(id, { $inc: { viewCount: 1 } });
    
    res.send({
      success: true,
      data: product
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取商品详情失败',
      error: error.message
    });
  }
});

// ========== 医院接口 ==========
// 获取医院列表
router.get('/hospitals', async (req, res) => {
  try {
    const { category, city, province, page = 1, limit = 10 } = req.query;
    let query = {};
    
    // 分类筛选
    if (category) {
      query.category = category;
    }
    
    // 地区筛选
    if (city && province) {
      query.city = city;
      query.province = province;
    }
    
    const skip = (page - 1) * limit;
    const hospitals = await hospitalModel.find(query)
      .populate('products', 'title price originalPrice saved image rating tags isHot viewCount') // 填充商品信息
      .sort({ isHot: -1, rating: -1, viewCount: -1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    const total = await hospitalModel.countDocuments(query);
    
    // 处理医院和商品图片URL - 使用自动获取的网络IP
    const processedHospitals = hospitals.map(hospital => {
      const hospitalObj = hospital.toObject();
      
      // 处理医院logo
      if (hospitalObj.logo) {
        hospitalObj.logo = processImageURL(hospitalObj.logo, '3000');
      }
      
      // 处理医院关联的商品图片
      if (hospitalObj.products && hospitalObj.products.length > 0) {
        hospitalObj.products = hospitalObj.products.map(product => ({
          ...product,
          image: processImageURL(product.image, '3000')
        }));
      }
      
      return hospitalObj;
    });
    
    res.send({
      success: true,
      data: processedHospitals,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取医院列表失败',
      error: error.message
    });
  }
});

  // 获取医院分类
  router.get('/hospitals/categories', async (req, res) => {
    try {
      // 先检查是否有数据
      const count = await hospitalModel.countDocuments();
      if (count === 0) {
        return res.send({
          success: true,
          data: ['热门', '民营', '公立']
        });
      }
      
      const categories = await hospitalModel.distinct('category');
      // 过滤掉空值并确保有默认分类
      const validCategories = categories.filter(cat => cat && cat.trim() !== '');
      const finalCategories = validCategories.length > 0 ? validCategories : ['热门'];
      
      res.send({
        success: true,
        data: finalCategories
      });
    } catch (error) {
      console.error('获取医院分类失败:', error);
      res.status(500).send({
        success: false,
        message: '获取医院分类失败',
        error: error.message
      });
    }
  });

// 获取医院详情
router.get('/hospitals/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const hospital = await hospitalModel.findById(id)
      .populate('products', 'title price originalPrice saved image rating tags isHot viewCount'); // 填充商品信息
    
    if (!hospital) {
      return res.status(404).send({
        success: false,
        message: '医院不存在'
      });
    }
    
    // 增加浏览次数
    await hospitalModel.findByIdAndUpdate(id, { $inc: { viewCount: 1 } });
    
    res.send({
      success: true,
      data: hospital
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取医院详情失败',
      error: error.message
    });
  }
});

// ========== 医生接口 ==========
// 获取医生列表
router.get('/doctors', async (req, res) => {
  try {
    const { category, city, province, page = 1, limit = 10 } = req.query;
    let query = {};
    
    // 分类筛选
    if (category) {
      query.category = category;
    }
    
    // 地区筛选
    if (city && province) {
      query.city = city;
      query.province = province;
    }
    
    const skip = (page - 1) * limit;
    const doctors = await doctorModel.find(query)
      .sort({ isHot: -1, viewCount: -1, createTime: -1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    const total = await doctorModel.countDocuments(query);
    
    res.send({
      success: true,
      data: doctors,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取医生列表失败',
      error: error.message
    });
  }
});

  // 获取医生分类
  router.get('/doctors/categories', async (req, res) => {
    try {
      // 先检查是否有数据
      const count = await doctorModel.countDocuments();
      if (count === 0) {
        return res.send({
          success: true,
          data: ['热门', '眼部整形', '美体塑形', '脂肪填充', '瘦脸轮廓']
        });
      }
      
      const categories = await doctorModel.distinct('category');
      // 过滤掉空值并确保有默认分类
      const validCategories = categories.filter(cat => cat && cat.trim() !== '');
      const finalCategories = validCategories.length > 0 ? validCategories : ['热门'];
      
      res.send({
        success: true,
        data: finalCategories
      });
    } catch (error) {
      console.error('获取医生分类失败:', error);
      res.status(500).send({
        success: false,
        message: '获取医生分类失败',
        error: error.message
      });
    }
  });

// 获取医生详情
router.get('/doctors/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const doctor = await doctorModel.findById(id);
    
    if (!doctor) {
      return res.status(404).send({
        success: false,
        message: '医生不存在'
      });
    }
    
    // 增加浏览次数
    await doctorModel.findByIdAndUpdate(id, { $inc: { viewCount: 1 } });
    
    res.send({
      success: true,
      data: doctor
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取医生详情失败',
      error: error.message
    });
  }
});

// ========== 用户相关接口 ==========
// 记录用户浏览历史
router.post('/users/view-history', async (req, res) => {
  try {
    const { openid, productId } = req.body;
    
    if (!openid || !productId) {
      return res.status(400).send({
        success: false,
        message: '缺少必要参数'
      });
    }
    
    // 查找或创建用户
    let user = await userModel.findOne({ openid });
    if (!user) {
      user = new userModel({ openid });
    }
    
    // 添加浏览历史
    user.viewHistory.push({
      productId,
      viewTime: new Date()
    });
    
    // 只保留最近50条浏览记录
    if (user.viewHistory.length > 50) {
      user.viewHistory = user.viewHistory.slice(-50);
    }
    
    await user.save();
    
    res.send({
      success: true,
      message: '浏览记录已保存'
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '保存浏览记录失败',
      error: error.message
    });
  }
});

// 获取用户推荐商品
router.get('/users/recommendations', async (req, res) => {
  try {
    const { openid, city, province, limit = 10 } = req.query;
    
    let query = {};
    
    // 地区筛选
    if (city && province) {
      query.city = city;
      query.province = province;
    }
    
    // 如果有用户信息，基于用户兴趣推荐
    if (openid) {
      const user = await userModel.findOne({ openid });
      if (user && user.interests && user.interests.length > 0) {
        // 基于用户兴趣推荐
        query.category = { $in: user.interests };
      }
    }
    
    const recommendations = await productModel.find(query)
      .sort({ isHot: -1, viewCount: -1 })
      .limit(parseInt(limit));
    
    res.send({
      success: true,
      data: recommendations
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取推荐商品失败',
      error: error.message
    });
  }
});

// ========== 搜索接口 ==========
// 全局搜索 - 针对前端筛选逻辑优化
router.get('/search', async (req, res) => {
  try {
    const { keyword, type = 'all', page = 1, limit = 10, tab = 'all' } = req.query;
    
    // 参数验证
    if (!keyword || keyword.trim() === '') {
      return res.send({
        success: true,
        data: {
          products: [],
          hospitals: [],
          doctors: [],
          total: 0,
          // 为前端提供筛选后的数据
          filteredResults: []
        }
      });
    }

    const searchKeyword = keyword.trim();
    const skip = (parseInt(page) - 1) * parseInt(limit);
    const limitNum = parseInt(limit);

    console.log(`搜索关键词: "${searchKeyword}", 类型: ${type}, 标签页: ${tab}, 页码: ${page}, 每页: ${limitNum}`);

    const results = {
      products: [],
      hospitals: [],
      doctors: [],
      total: 0,
      filteredResults: [] // 根据当前标签页筛选的结果
    };

    // 并行搜索，提高性能
    const searchPromises = [];

    // 搜索商品 - 支持更多字段搜索
    if (type === 'all' || type === 'products') {
      searchPromises.push(
        productModel.find({
          $or: [
            { title: { $regex: searchKeyword, $options: 'i' } },
            { tags: { $regex: searchKeyword, $options: 'i' } },
            { 'hospitals.hospitalName': { $regex: searchKeyword, $options: 'i' } }
          ]
        })
        .populate('category', 'name')
        .sort({ isHot: -1, viewCount: -1, createTime: -1 })
        .skip(skip)
        .limit(limitNum)
        .then(products => {
          // 处理商品数据，确保格式一致
          const processedProducts = products.map(product => ({
            ...product.toObject(),
            // 确保图片URL正确
            image: product.image ? (product.image.startsWith('http') ? product.image : `${req.protocol}://${req.get('host')}${product.image}`) : '',
            // 添加搜索匹配信息
            searchMatch: {
              title: product.title?.toLowerCase().includes(searchKeyword.toLowerCase()),
              tags: product.tags?.some(tag => tag.toLowerCase().includes(searchKeyword.toLowerCase())),
              hospital: product.hospitals?.some(h => h.hospitalName?.toLowerCase().includes(searchKeyword.toLowerCase()))
            }
          }));
          
          results.products = processedProducts;
          return processedProducts.length;
        })
      );
    }

    // 搜索医院 - 支持更多字段搜索
    if (type === 'all' || type === 'hospitals') {
      searchPromises.push(
        hospitalModel.find({
          $or: [
            { name: { $regex: searchKeyword, $options: 'i' } },
            { tag: { $regex: searchKeyword, $options: 'i' } },
            { city: { $regex: searchKeyword, $options: 'i' } },
            { province: { $regex: searchKeyword, $options: 'i' } },
            { location: { $regex: searchKeyword, $options: 'i' } }
          ]
        })
        .populate('products', 'title price originalPrice saved image rating tags isHot viewCount')
        .sort({ isHot: -1, rating: -1, viewCount: -1 })
        .skip(skip)
        .limit(limitNum)
        .then(hospitals => {
          results.hospitals = hospitals;
          return hospitals.length;
        })
      );
    }

    // 搜索医生 - 支持更多字段搜索
    if (type === 'all' || type === 'doctors') {
      searchPromises.push(
        doctorModel.find({
          $or: [
            { name: { $regex: searchKeyword, $options: 'i' } },
            { hospital: { $regex: searchKeyword, $options: 'i' } },
            { specialties: { $regex: searchKeyword, $options: 'i' } },
            { city: { $regex: searchKeyword, $options: 'i' } },
            { province: { $regex: searchKeyword, $options: 'i' } }
          ]
        })
        .sort({ isHot: -1, viewCount: -1, createTime: -1 })
        .skip(skip)
        .limit(limitNum)
        .then(doctors => {
          results.doctors = doctors;
          return doctors.length;
        })
      );
    }

    // 等待所有搜索完成
    if (searchPromises.length > 0) {
      const counts = await Promise.all(searchPromises);
      results.total = counts.reduce((sum, count) => sum + count, 0);
    }

    // 根据当前标签页筛选结果，方便前端直接使用
    if (tab === '钜惠商品' || tab === 'products') {
      results.filteredResults = results.products;
    } else if (tab === '甄选机构' || tab === 'hospitals') {
      results.filteredResults = results.hospitals;
    } else if (tab === '口碑医生' || tab === 'doctors') {
      results.filteredResults = results.doctors;
    } else {
      // 全部标签页，合并所有结果
      results.filteredResults = [
        ...results.products.map(p => ({ ...p, _type: 'product' })),
        ...results.hospitals.map(h => ({ ...h, _type: 'hospital' })),
        ...results.doctors.map(d => ({ ...d, _type: 'doctor' }))
      ];
    }

    console.log(`搜索完成: 商品${results.products.length}个, 医院${results.hospitals.length}个, 医生${results.doctors.length}个, 筛选结果${results.filteredResults.length}个`);

    res.send({
      success: true,
      data: results
    });
  } catch (error) {
    console.error('搜索失败:', error);
    res.status(500).send({
      success: false,
      message: '搜索失败',
      error: error.message
    });
  }
});

// 搜索建议 - 重新设计，更简洁高效
router.get('/search/suggestions', async (req, res) => {
  try {
    const { keyword, limit = 10 } = req.query;
    
    if (!keyword || keyword.trim() === '') {
      return res.send({
        success: true,
        data: []
      });
    }

    const searchKeyword = keyword.trim();
    const limitNum = parseInt(limit);

    console.log(`获取搜索建议: "${searchKeyword}", 限制: ${limitNum}`);

    // 并行获取建议，提高性能
    const [productSuggestions, hospitalSuggestions, doctorSuggestions] = await Promise.all([
      // 商品建议
      productModel.find({
        title: { $regex: searchKeyword, $options: 'i' }
      })
      .select('title')
      .limit(limitNum)
      .sort({ viewCount: -1 }),

      // 医院建议
      hospitalModel.find({
        name: { $regex: searchKeyword, $options: 'i' }
      })
      .select('name')
      .limit(limitNum)
      .sort({ viewCount: -1 }),

      // 医生建议
      doctorModel.find({
        name: { $regex: searchKeyword, $options: 'i' }
      })
      .select('name')
      .limit(limitNum)
      .sort({ viewCount: -1 })
    ]);

    // 合并所有建议
    const suggestions = [
      ...productSuggestions.map(p => ({ type: 'product', name: p.title })),
      ...hospitalSuggestions.map(h => ({ type: 'hospital', name: h.name })),
      ...doctorSuggestions.map(d => ({ type: 'doctor', name: d.name }))
    ];

    // 去重并限制数量
    const uniqueSuggestions = suggestions
      .filter((item, index, self) => 
        index === self.findIndex(t => t.name === item.name)
      )
      .slice(0, limitNum);

    console.log(`搜索建议完成: ${uniqueSuggestions.length}个建议`);

    res.send({
      success: true,
      data: uniqueSuggestions
    });
  } catch (error) {
    console.error('获取搜索建议失败:', error);
    res.status(500).send({
      success: false,
      message: '获取搜索建议失败',
      error: error.message
    });
  }
});

// 标签页搜索 - 专门用于前端标签页筛选
router.get('/search/tab', async (req, res) => {
  try {
    const { keyword, tab, page = 1, limit = 10 } = req.query;
    
    if (!keyword || keyword.trim() === '') {
      return res.send({
        success: true,
        data: []
      });
    }

    const searchKeyword = keyword.trim();
    const skip = (parseInt(page) - 1) * parseInt(limit);
    const limitNum = parseInt(limit);

    console.log(`标签页搜索: "${searchKeyword}", 标签页: ${tab}, 页码: ${page}, 每页: ${limitNum}`);

    let results = [];

    // 根据标签页类型进行搜索
    switch (tab) {
      case '钜惠商品':
      case 'products':
        results = await productModel.find({
          $or: [
            { title: { $regex: searchKeyword, $options: 'i' } },
            { tags: { $regex: searchKeyword, $options: 'i' } },
            { 'hospitals.hospitalName': { $regex: searchKeyword, $options: 'i' } }
          ]
        })
        .populate('category', 'name')
        .sort({ isHot: -1, viewCount: -1, createTime: -1 })
        .skip(skip)
        .limit(limitNum);
        
        // 处理商品数据
        results = results.map(product => ({
          ...product.toObject(),
          image: product.image ? (product.image.startsWith('http') ? product.image : `${req.protocol}://${req.get('host')}${product.image}`) : '',
          _type: 'product'
        }));
        break;

      case '甄选机构':
      case 'hospitals':
        results = await hospitalModel.find({
          $or: [
            { name: { $regex: searchKeyword, $options: 'i' } },
            { tag: { $regex: searchKeyword, $options: 'i' } },
            { city: { $regex: searchKeyword, $options: 'i' } },
            { province: { $regex: searchKeyword, $options: 'i' } },
            { location: { $regex: searchKeyword, $options: 'i' } }
          ]
        })
        .populate('products', 'title price originalPrice saved image rating tags isHot viewCount')
        .sort({ isHot: -1, rating: -1, viewCount: -1 })
        .skip(skip)
        .limit(limitNum);
        
        results = results.map(hospital => ({
          ...hospital.toObject(),
          _type: 'hospital'
        }));
        break;

      case '口碑医生':
      case 'doctors':
        results = await doctorModel.find({
          $or: [
            { name: { $regex: searchKeyword, $options: 'i' } },
            { hospital: { $regex: searchKeyword, $options: 'i' } },
            { specialties: { $regex: searchKeyword, $options: 'i' } },
            { city: { $regex: searchKeyword, $options: 'i' } },
            { province: { $regex: searchKeyword, $options: 'i' } }
          ]
        })
        .sort({ isHot: -1, viewCount: -1, createTime: -1 })
        .skip(skip)
        .limit(limitNum);
        
        results = results.map(doctor => ({
          ...doctor.toObject(),
          _type: 'doctor'
        }));
        break;

      default:
        return res.status(400).send({
          success: false,
          message: '无效的标签页类型'
        });
    }

    console.log(`标签页搜索完成: ${results.length}个结果`);

    res.send({
      success: true,
      data: results
    });
  } catch (error) {
    console.error('标签页搜索失败:', error);
    res.status(500).send({
      success: false,
      message: '标签页搜索失败',
      error: error.message
    });
  }
});

// 快速搜索 - 专门用于搜索框的实时搜索
router.get('/search/quick', async (req, res) => {
  try {
    const { keyword, limit = 5 } = req.query;
    
    if (!keyword || keyword.trim() === '') {
      return res.send({
        success: true,
        data: []
      });
    }

    const searchKeyword = keyword.trim();
    const limitNum = parseInt(limit);

    console.log(`快速搜索: "${searchKeyword}"`);

    // 并行搜索，只返回基本信息
    const [products, hospitals, doctors] = await Promise.all([
      // 商品快速搜索
      productModel.find({
        title: { $regex: searchKeyword, $options: 'i' }
      })
      .select('title price image tags')
      .sort({ isHot: -1, viewCount: -1 })
      .limit(limitNum),

      // 医院快速搜索
      hospitalModel.find({
        name: { $regex: searchKeyword, $options: 'i' }
      })
      .select('name rating city tag')
      .sort({ isHot: -1, rating: -1 })
      .limit(limitNum),

      // 医生快速搜索
      doctorModel.find({
        name: { $regex: searchKeyword, $options: 'i' }
      })
      .select('name hospital city specialties')
      .sort({ isHot: -1, viewCount: -1 })
      .limit(limitNum)
    ]);

    // 格式化结果
    const results = [
      ...products.map(p => ({
        type: 'product',
        id: p._id,
        name: p.title,
        price: p.price,
        image: p.image,
        tags: p.tags,
        description: `¥${p.price}`
      })),
      ...hospitals.map(h => ({
        type: 'hospital',
        id: h._id,
        name: h.name,
        rating: h.rating,
        city: h.city,
        tag: h.tag,
        description: `${h.city} | ${h.rating}分`
      })),
      ...doctors.map(d => ({
        type: 'doctor',
        id: d._id,
        name: d.name,
        hospital: d.hospital,
        city: d.city,
        specialties: d.specialties,
        description: `${d.hospital} | ${d.city}`
      }))
    ];

    // 按相关性排序（简单按名称匹配度）
    results.sort((a, b) => {
      const aMatch = a.name.toLowerCase().indexOf(searchKeyword.toLowerCase());
      const bMatch = b.name.toLowerCase().indexOf(searchKeyword.toLowerCase());
      return aMatch - bMatch;
    });

    console.log(`快速搜索完成: ${results.length}个结果`);

    res.send({
      success: true,
      data: results
    });
  } catch (error) {
    console.error('快速搜索失败:', error);
    res.status(500).send({
      success: false,
      message: '快速搜索失败',
      error: error.message
    });
  }
});

// ========== 数据大屏统计接口 ==========
// 获取核心指标数据
router.get('/dashboard/core-metrics', async (req, res) => {
  try {
    const { city } = req.query;
    let productDoctorQuery = {};
    let hospitalQuery = {};

    if (city) {
      // 查找该城市的医院
      const hospitalsInCity = await hospitalModel.find({
        $or: [
          { city: city },
          { city: city.replace('市', '') },
          { city: city + '市' }
        ]
      }).select('name');

      const hospitalNamesInCity = hospitalsInCity.map(h => h.name);

      if (hospitalNamesInCity.length === 0) {
        return res.send({
          success: true,
          data: {
            totalProducts: 0,
            totalHospitals: 0,
            totalDoctors: 0,
            lastUpdate: new Date()
          }
        });
      }

      // 根据医院名称筛选产品和医生
      productDoctorQuery = { hospital: { $in: hospitalNamesInCity } };
      hospitalQuery = {
        $or: [
          { city: city },
          { city: city.replace('市', '') },
          { city: city + '市' }
        ]
      };
    }

    const [
      totalProducts,
      totalHospitals,
      totalDoctors
    ] = await Promise.all([
      productModel.countDocuments(productDoctorQuery),
      hospitalModel.countDocuments(hospitalQuery),
      doctorModel.countDocuments(productDoctorQuery)
    ]);

    res.send({
      success: true,
      data: {
        totalProducts,
        totalHospitals,
        totalDoctors,
        lastUpdate: new Date()
      }
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取核心指标失败',
      error: error.message
    });
  }
});

// 获取商品销量TOP10排行榜
router.get('/dashboard/product-top10', async (req, res) => {
  try {
    const topProducts = await productModel.find({})
      .sort({ viewCount: -1 })
      .limit(10)
      .select('title price viewCount hospital category');

    res.send({
      success: true,
      data: topProducts
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取商品排行榜失败',
      error: error.message
    });
  }
});

// 获取价格分析数据
router.get('/dashboard/price-analysis', async (req, res) => {
  try {
    const priceRanges = await productModel.aggregate([
      {
        $bucket: {
          groupBy: '$price',
          boundaries: [0, 500, 1000, 2000, 5000, 10000, Infinity],
          default: '10000+',
          output: {
            count: { $sum: 1 },
            avgPrice: { $avg: '$price' }
          }
        }
      }
    ]);

    res.send({
      success: true,
      data: priceRanges
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取价格分析失败',
      error: error.message
    });
  }
});

// 获取医生专业分布数据
router.get('/dashboard/doctor-specialties', async (req, res) => {
  try {
    const specialties = await doctorModel.aggregate([
      { $unwind: '$specialties' },
      {
        $group: {
          _id: '$specialties',
          count: { $sum: 1 }
        }
      },
      { $sort: { count: -1 } },
      { $limit: 6 }  // 只返回前6个专业
    ]);

    // 转换数据格式以匹配前端期望
    const formattedData = specialties.map(item => ({
      _id: item._id,
      specialty: item._id,
      count: item.count,
      percentage: ((item.count / specialties.reduce((sum, s) => sum + s.count, 0)) * 100).toFixed(1)
    }));

    res.send({
      success: true,
      data: formattedData
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取医生专业分布失败',
      error: error.message
    });
  }
});

// 获取医院分布数据
router.get('/dashboard/hospital-distribution', async (req, res) => {
  try {
    console.log('开始获取医院分布数据...')
    
    const distribution = await hospitalModel.aggregate([
      {
        $group: {
          _id: {
            // 使用省份作为主要分组键，与前端逻辑保持一致
            province: { $ifNull: ['$province', '$city'] }
          },
          count: { $sum: 1 },
          hospitals: { 
            $push: { 
              name: '$name', 
              rating: '$rating',
              location: '$location', // 使用location而不是address
              category: '$category',
              isHot: '$isHot',
              services: '$services',
              reviews: '$reviews',
              doctors: '$doctors'
            } 
          },
          avgRating: { $avg: '$rating' },
          // 保存第一个城市的名称作为city字段
          firstCity: { $first: '$city' }
        }
      },
      { $sort: { count: -1 } }
    ]);

    console.log('医院分布聚合结果:', distribution)

    // 为地图提供格式化的数据
    const mapData = distribution.map(item => ({
      name: item._id.province || '未知省份',
      city: item.firstCity || item._id.province || '未知城市',
      province: item._id.province || '未知省份',
      value: item.count,
      hospitals: item.hospitals,
      avgRating: Math.round(item.avgRating * 10) / 10
    }));

    console.log('格式化后的地图数据:', mapData)

    res.send({
      success: true,
      data: mapData
    });
  } catch (error) {
    console.error('获取医院分布失败:', error)
    res.status(500).send({
      success: false,
      message: '获取医院分布失败',
      error: error.message
    });
  }
});

// 获取地图医院详情数据
router.get('/dashboard/map-hospitals', async (req, res) => {
  try {
    const { province, city } = req.query;
    let query = {};
    
    if (province) {
      query.province = province;
    }
    if (city) {
      query.city = city;
    }

    const hospitals = await hospitalModel.find(query)
      .select('name rating address category isHot province city')
      .sort({ rating: -1, isHot: -1 })
      .limit(50);

    res.send({
      success: true,
      data: hospitals
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取地图医院数据失败',
      error: error.message
    });
  }
});

// ========== 数据大屏双向通信接口 ==========
// 订阅数据大屏更新
router.post('/dashboard/subscribe', async (req, res) => {
  try {
    const { userId } = req.body;
    if (!userId) {
      return res.status(400).send({
        success: false,
        message: '缺少用户ID'
      });
    }

    const io = req.app.get('io');
    if (io) {
      // 用户加入数据大屏房间
      const socket = io.sockets.sockets.get(userId);
      if (socket) {
        socket.join('dashboard:updates');
      }
    }

    res.send({
      success: true,
      message: '订阅数据大屏更新成功'
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '订阅失败',
      error: error.message
    });
  }
});

// 获取城市医生数据
router.get('/dashboard/city-doctors/:city', async (req, res) => {
  try {
    const { city } = req.params
    console.log(`获取${city}的医生数据...`)
    
    // 查找该城市的医生
    const doctors = await doctorModel.find({ city: city })
    console.log(`${city}找到${doctors.length}个医生`)
    
    res.send({
      success: true,
      data: doctors
    })
  } catch (error) {
    console.error('获取城市医生数据失败:', error)
    res.status(500).send({
      success: false,
      message: '获取城市医生数据失败'
    })
  }
})

// 获取省份数据概览 - 用于地图显示
router.get('/dashboard/province-overview', async (req, res) => {
  try {
    console.log('获取省份数据概览...')
    
    const provinceOverview = await hospitalModel.aggregate([
      {
        $group: {
          _id: '$province',
          hospitalCount: { $sum: 1 },
          avgRating: { $avg: '$rating' },
          cities: { $addToSet: '$city' },
          totalDoctors: { $sum: { $size: '$doctor' } }
        }
      },
      {
        $project: {
          province: '$_id',
          hospitalCount: 1,
          avgRating: { $round: ['$avgRating', 1] },
          cityCount: { $size: '$cities' },
          totalDoctors: 1,
          hasData: { $gt: ['$hospitalCount', 0] }
        }
      },
      { $sort: { hospitalCount: -1 } }
    ])
    
    console.log('省份数据概览:', provinceOverview)
    
    res.send({
      success: true,
      data: provinceOverview
    })
  } catch (error) {
    console.error('获取省份数据概览失败:', error)
    res.status(500).send({
      success: false,
      message: '获取省份数据概览失败',
      error: error.message
    })
  }
})

// 获取省份详细数据 - 支持省级联动
router.get('/dashboard/province-data/:province', async (req, res) => {
  try {
    const { province } = req.params
    console.log(`获取${province}的省份数据...`)
    
    // 检查省份是否有数据
    const hasData = await hospitalModel.findOne({ province: province })
    if (!hasData) {
      return res.send({
        success: true,
        data: {
          hasData: false,
          message: `${province}暂无相关数据`,
          coreMetrics: { totalProducts: 0, totalHospitals: 0, totalDoctors: 0 },
          products: [],
          doctors: [],
          hospitals: []
        }
      })
    }
    
    // 并行获取省份相关数据
    const [hospitals, doctors, products] = await Promise.all([
      // 获取省份医院数据
      hospitalModel.find({ province: province })
        .populate('products', 'title price viewCount')
        .populate('doctor', 'name specialties')
        .select('name rating location city category isHot viewCount products doctor')
        .sort({ rating: -1, isHot: -1 }),
      
      // 获取省份医生数据
      doctorModel.find({ province: province })
        .select('name hospital specialties city isHot viewCount')
        .sort({ isHot: -1, viewCount: -1 }),
      
      // 获取省份产品数据（通过医院关联）
      productModel.find({ 
        'hospitals.hospitalName': { 
          $in: await hospitalModel.find({ province: province }).distinct('name')
        }
      })
        .select('title price hospital viewCount')
        .sort({ viewCount: -1 })
        .limit(10)
    ])
    
    // 计算核心指标
    const coreMetrics = {
      totalProducts: products.length,
      totalHospitals: hospitals.length,
      totalDoctors: doctors.length
    }
    
    // 生成医生专业分布
    const specialtyCount = {}
    doctors.forEach(doctor => {
      if (doctor.specialties && doctor.specialties.length > 0) {
        doctor.specialties.forEach(specialty => {
          specialtyCount[specialty] = (specialtyCount[specialty] || 0) + 1
        })
      } else {
        // 如果没有specialties，使用category
        const specialty = doctor.category || '其他'
        specialtyCount[specialty] = (specialtyCount[specialty] || 0) + 1
      }
    })
    
    const doctorSpecialties = Object.entries(specialtyCount).map(([specialty, count]) => ({
      specialty,
      count,
      percentage: doctors.length > 0 ? ((count / doctors.length) * 100).toFixed(1) : '0.0'
    }))
    
    const provinceData = {
      hasData: true,
      province: province,
      coreMetrics,
      products,
      doctors: doctorSpecialties,
      hospitals
    }
    
    console.log(`${province}的省份数据:`, provinceData)
    
    res.send({
      success: true,
      data: provinceData
    })
  } catch (error) {
    console.error(`获取${province}省份数据失败:`, error)
    res.status(500).send({
      success: false,
      message: '获取省级数据失败',
      error: error.message
    })
  }
})

// 获取所有数据 - 用于Socket.IO
const getAllData = async () => {
  try {
    console.log('获取所有数据...')
    
    // 并行获取所有数据
    const [coreMetrics, productTop10, doctorSpecialties, hospitalDistribution, priceAnalysis, provinceOverview] = await Promise.all([
      // 核心指标
      (async () => {
        const [totalProducts, totalHospitals, totalDoctors] = await Promise.all([
          productModel.countDocuments(),
          hospitalModel.countDocuments(),
          doctorModel.countDocuments()
        ])
        return { totalProducts, totalHospitals, totalDoctors }
      })(),
      
      // 商品TOP10
      productModel.find()
        .select('title price hospital viewCount')
        .sort({ viewCount: -1 })
        .limit(10),
      
      // 医生专业分布
      (async () => {
        const doctors = await doctorModel.find()
        const specialtyCount = {}
        doctors.forEach(doctor => {
          if (doctor.specialties && doctor.specialties.length > 0) {
            doctor.specialties.forEach(specialty => {
              specialtyCount[specialty] = (specialtyCount[specialty] || 0) + 1
            })
          } else {
            const specialty = doctor.category || '其他'
            specialtyCount[specialty] = (specialtyCount[specialty] || 0) + 1
          }
        })
        return Object.entries(specialtyCount).map(([specialty, count]) => ({
          specialty,
          count,
          percentage: doctors.length > 0 ? ((count / doctors.length) * 100).toFixed(1) : '0.0'
        }))
      })(),
      
      // 医院分布
      hospitalModel.aggregate([
        {
          $group: {
            _id: '$city',
            hospitalCount: { $sum: 1 },
            avgRating: { $avg: '$rating' },
            hospitals: { $push: { name: '$name', rating: '$rating', address: '$location', category: '$category', isHot: '$isHot' } }
          }
        },
        {
          $project: {
            name: '$_id',
            city: '$_id',
            value: '$hospitalCount',
            avgRating: { $round: ['$avgRating', 1] },
            hospitals: 1
          }
        },
        { $sort: { value: -1 } }
      ]),
      
      // 价格分析
      (async () => {
        const products = await productModel.find().select('price')
        const priceRanges = [
          { name: '500-1000', min: 500, max: 1000, color: '#00ffff' },
          { name: '1000-2000', min: 1000, max: 2000, color: '#ff00ff' },
          { name: '2000-3000', min: 2000, max: 3000, color: '#ffff00' },
          { name: '3000-5000', min: 3000, max: 5000, color: '#00ff00' },
          { name: '5000+', min: 5000, max: Infinity, color: '#ff6600' }
        ]
        return priceRanges.map(range => {
          const count = products.filter(p => p.price >= range.min && p.price < range.max).length
          return { name: range.name, value: count, color: range.color }
        })
      })(),
      
      // 省份概览
      hospitalModel.aggregate([
        {
          $group: {
            _id: '$province',
            hospitalCount: { $sum: 1 },
            avgRating: { $avg: '$rating' },
            cities: { $addToSet: '$city' },
            totalDoctors: { $sum: { $size: '$doctor' } }
          }
        },
        {
          $project: {
            province: '$_id',
            hospitalCount: 1,
            avgRating: { $round: ['$avgRating', 1] },
            cityCount: { $size: '$cities' },
            totalDoctors: 1,
            hasData: { $gt: ['$hospitalCount', 0] }
          }
        },
        { $sort: { hospitalCount: -1 } }
      ])
    ])
    
    const allData = {
      coreMetrics,
      productTop10,
      doctorSpecialties,
      hospitalDistribution,
      priceAnalysis,
      provinceOverview,
      timestamp: new Date()
    }
    
    console.log('所有数据获取完成:', allData)
    return allData
  } catch (error) {
    console.error('获取所有数据失败:', error)
    throw error
  }
}



// 获取所有数据用于前端缓存
router.get('/dashboard/all-data', async (req, res) => {
  try {
    console.log('开始获取所有数据...')
    
    // 并行获取所有数据
    const [
      coreMetrics,
      productTop10,
      doctorSpecialties,
      hospitalDistribution,
      priceAnalysis
    ] = await Promise.all([
      // 核心指标
      Promise.all([
        userModel.countDocuments(),
        productModel.countDocuments(),
        hospitalModel.countDocuments(),
        doctorModel.countDocuments()
      ]).then(([totalUsers, totalProducts, totalHospitals, totalDoctors]) => ({
        totalUsers,
        totalProducts,
        totalHospitals,
        totalDoctors
      })),
      
      // 商品TOP10
      productModel.find({})
        .sort({ viewCount: -1 })
        .limit(10)
        .select('title price viewCount hospital category'),
      
      // 医生专业分布 - 基于实际医生数量计算
      Promise.all([
        doctorModel.aggregate([
          { $unwind: '$specialties' },
          {
            $group: {
              _id: '$specialties',
              count: { $sum: 1 }
            }
          },
          { $sort: { count: -1 } },
          { $limit: 6 }
        ]),
        doctorModel.countDocuments()
      ]).then(([specialties, totalDoctors]) => {
        // 按比例分配医生到各个专业，确保总数与核心指标一致
        const totalSpecialtyCount = specialties.reduce((sum, s) => sum + s.count, 0)
        const scaleFactor = totalDoctors / totalSpecialtyCount
        
        return specialties.map(item => ({
          specialty: item._id,
          count: Math.round(item.count * scaleFactor),
          percentage: ((item.count / totalSpecialtyCount) * 100).toFixed(1)
        }))
      }),
      
      // 医院分布
      hospitalModel.aggregate([
        {
          $group: {
            _id: {
              // 使用省份作为主要分组键，与前端逻辑保持一致
              province: { $ifNull: ['$province', '$city'] }
            },
            count: { $sum: 1 },
            hospitals: { 
              $push: { 
                name: '$name', 
                rating: '$rating',
                location: '$location',
                category: '$category',
                isHot: '$isHot',
                services: '$services',
                reviews: '$reviews',
                doctors: '$doctors'
              } 
            },
            avgRating: { $avg: '$rating' },
            // 保存第一个城市的名称作为city字段
            firstCity: { $first: '$city' }
          }
        },
        { $sort: { count: -1 } }
      ]).then(distribution => distribution.map(item => ({
        name: item._id.province || '未知省份',
        city: item.firstCity || item._id.province || '未知城市',
        province: item._id.province || '未知省份',
        value: item.count,
        hospitals: item.hospitals,
        avgRating: Math.round(item.avgRating * 10) / 10
      }))),
      
      // 价格分析
      productModel.aggregate([
        {
          $bucket: {
            groupBy: '$price',
            boundaries: [0, 500, 1000, 2000, 3000, 5000, Infinity],
            default: '5000+',
            output: {
              count: { $sum: 1 },
              avgPrice: { $avg: '$price' }
            }
          }
        }
      ]).then(buckets => buckets.map((bucket, index) => {
        const colors = ['#00ffff', '#ff00ff', '#ffff00', '#00ff00', '#ff6600', '#ff0000']
        const ranges = ['500-1000', '1000-2000', '2000-3000', '3000-5000', '5000+', '10000+']
        return {
          name: ranges[index] || bucket._id,
          value: bucket.count,
          color: colors[index] || '#00ffff'
        }
      }))
    ]);

    const allData = {
      coreMetrics,
      productTop10,
      doctorSpecialties,
      hospitalDistribution,
      priceAnalysis,
      timestamp: new Date()
    };

    console.log('所有数据获取完成:', allData)
    
    res.send({
      success: true,
      data: allData
    });
  } catch (error) {
    console.error('获取所有数据失败:', error)
    res.status(500).send({
      success: false,
      message: '获取所有数据失败',
      error: error.message
    });
  }
});

// 推送数据大屏更新
router.post('/dashboard/push-update', async (req, res) => {
  try {
    const { updateType, data } = req.body;
    const io = req.app.get('io');
    
    if (io) {
      // 向所有订阅数据大屏的用户推送更新
      io.to('dashboard:updates').emit('dashboard:update', {
        type: updateType,
        data: data,
        timestamp: new Date()
      });
    }

    res.send({
      success: true,
      message: '数据大屏更新推送成功'
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '推送更新失败',
      error: error.message
    });
  }
});

// 取消订阅数据大屏更新
router.post('/dashboard/unsubscribe', async (req, res) => {
  try {
    const { userId } = req.body;
    if (!userId) {
      return res.status(400).send({
        success: false,
        message: '缺少用户ID'
      });
    }

    const io = req.app.get('io');
    if (io) {
      const socket = io.sockets.sockets.get(userId);
      if (socket) {
        socket.leave('dashboard:updates');
      }
    }

    res.send({
      success: true,
      message: '取消订阅数据大屏更新成功'
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '取消订阅失败',
      error: error.message
    });
  }
});

// 获取实时数据大屏统计
router.get('/dashboard/realtime-stats', async (req, res) => {
  try {
    const io = req.app.get('io');
    let connectedUsers = 0;
    
    if (io) {
      // 获取连接到数据大屏房间的用户数量
      const dashboardRoom = io.sockets.adapter.rooms.get('dashboard:updates');
      connectedUsers = dashboardRoom ? dashboardRoom.size : 0;
    }

    // 获取最新的统计数据
    const [
      totalUsers,
      totalProducts,
      totalHospitals,
      totalDoctors
    ] = await Promise.all([
      userModel.countDocuments(),
      productModel.countDocuments(),
      hospitalModel.countDocuments(),
      doctorModel.countDocuments()
    ]);

    res.send({
      success: true,
      data: {
        connectedUsers,
        totalUsers,
        totalProducts,
        totalHospitals,
        totalDoctors,
        lastUpdate: new Date()
      }
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取实时统计失败',
      error: error.message
    });
  }
});

// ========== 城市数据接口 ==========
// 获取指定城市的商品数据
router.get('/dashboard/city-products', async (req, res) => {
  try {
    const { city } = req.query;
    
    if (!city) {
      return res.status(400).send({
        success: false,
        message: '缺少城市参数'
      });
    }

    // 查找该城市的医院
    const hospitals = await hospitalModel.find({ 
      $or: [
        { city: city },
        { city: city.replace('市', '') },
        { city: city + '市' }
      ]
    });

    if (hospitals.length === 0) {
      return res.send({
        success: true,
        data: []
      });
    }

    // 获取医院名称列表
    const hospitalNames = hospitals.map(h => h.name);

    // 获取这些医院的商品，按浏览次数排序
    const products = await productModel.find({
      hospital: { $in: hospitalNames }
    })
    .sort({ viewCount: -1 })
    .limit(10);

    // 格式化数据
    const formattedProducts = products.map(product => ({
      _id: product._id,
      title: product.title,
      name: product.title, // 使用title作为name
      price: product.price,
      hospital: product.hospital,
      viewCount: product.viewCount || 0
    }));

    res.send({
      success: true,
      data: formattedProducts
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取城市商品数据失败',
      error: error.message
    });
  }
});

// 获取指定城市的医院数据
router.get('/dashboard/city-hospitals', async (req, res) => {
  try {
    const { city } = req.query;
    
    if (!city) {
      return res.status(400).send({
        success: false,
        message: '缺少城市参数'
      });
    }

    // 查找该城市的医院
    const hospitals = await hospitalModel.find({ 
      $or: [
        { city: city },
        { city: city.replace('市', '') },
        { city: city + '市' }
      ]
    });

    // 格式化医院数据
    const formattedHospitals = hospitals.map(hospital => ({
      name: hospital.name,
      rating: hospital.rating || 4.5,
      address: hospital.address,
      category: hospital.category,
      isHot: hospital.isHot || false,
      doctors: hospital.doctors || 0
    }));

    res.send({
      success: true,
      data: formattedHospitals
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取城市医院数据失败',
      error: error.message
    });
  }
});

// 获取指定城市的医生专业分布数据
router.get('/dashboard/city-doctors', async (req, res) => {
  try {
    const { city } = req.query;
    
    if (!city) {
      return res.status(400).send({
        success: false,
        message: '缺少城市参数'
      });
    }

    // 查找该城市的医院
    const hospitals = await hospitalModel.find({ 
      $or: [
        { city: city },
        { city: city.replace('市', '') },
        { city: city + '市' }
      ]
    });

    if (hospitals.length === 0) {
      return res.send({
        success: true,
        data: []
      });
    }

    // 获取医院名称列表
    const hospitalNames = hospitals.map(h => h.name);

    // 获取这些医院的医生
    const doctors = await doctorModel.find({
      hospital: { $in: hospitalNames }
    });

    // 按专业分组统计 - 使用specialties数组
    const specialtyStats = {};
    doctors.forEach(doctor => {
      // 遍历医生的所有专业
      if (doctor.specialties && doctor.specialties.length > 0) {
        doctor.specialties.forEach(specialty => {
          if (!specialtyStats[specialty]) {
            specialtyStats[specialty] = 0;
          }
          specialtyStats[specialty]++;
        });
      } else {
        // 如果没有specialties数组，使用category字段
        const specialty = doctor.category || '其他';
        if (!specialtyStats[specialty]) {
          specialtyStats[specialty] = 0;
        }
        specialtyStats[specialty]++;
      }
    });

    // 计算总数和百分比
    const totalDoctors = doctors.length;
    const specialtyData = Object.entries(specialtyStats).map(([specialty, count]) => ({
      specialty,
      count,
      percentage: totalDoctors > 0 ? ((count / totalDoctors) * 100).toFixed(1) : '0.0'
    })).sort((a, b) => b.count - a.count);

    res.send({
      success: true,
      data: specialtyData
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: '获取城市医生数据失败',
      error: error.message
    });
  }
});

// ========== 数据变化监听和自动推送 ==========
// 数据变化推送函数
const pushDataUpdate = (updateType, data) => {
  try {
    const io = require('../app').get('io');
    if (io) {
      console.log(`推送数据更新: ${updateType}`, data);
      io.to('dashboard:updates').emit('dashboard:update', {
        updateType: updateType,
        data: data,
        timestamp: new Date()
      });
    }
  } catch (error) {
    console.error('推送数据更新失败:', error);
  }
};

// 监听数据变化并自动推送
const setupDataChangeListeners = () => {
  try {
    // 监听商品变化
    productModel.watch().on('change', async (change) => {
      console.log('商品数据变化:', change.operationType);
      
      if (['insert', 'update', 'delete'].includes(change.operationType)) {
        // 重新获取商品TOP10数据
        const productTop10 = await productModel.find({})
          .sort({ viewCount: -1 })
          .limit(10)
          .select('title price viewCount hospital category');
        
        pushDataUpdate('product-top10', productTop10);
        
        // 重新获取价格分析数据
        const priceAnalysis = await productModel.aggregate([
          {
            $bucket: {
              groupBy: '$price',
              boundaries: [0, 500, 1000, 2000, 5000, 10000, Infinity],
              default: '10000+',
              output: {
                count: { $sum: 1 },
                avgPrice: { $avg: '$price' }
              }
            }
          }
        ]);
        
        pushDataUpdate('price-analysis', priceAnalysis);
        
        // 更新核心指标
        const totalProducts = await productModel.countDocuments();
        pushDataUpdate('core-metrics', { totalProducts });
      }
    });

    // 监听医生变化
    doctorModel.watch().on('change', async (change) => {
      console.log('医生数据变化:', change.operationType);
      
      if (['insert', 'update', 'delete'].includes(change.operationType)) {
        // 重新获取医生专业分布数据
        const doctorSpecialties = await doctorModel.aggregate([
          { $unwind: '$specialties' },
          {
            $group: {
              _id: '$specialties',
              count: { $sum: 1 }
            }
          },
          { $sort: { count: -1 } },
          { $limit: 6 }
        ]).then(specialties => specialties.map(item => ({
          specialty: item._id,
          count: item.count,
          percentage: ((item.count / specialties.reduce((sum, s) => sum + s.count, 0)) * 100).toFixed(1)
        })));
        
        pushDataUpdate('doctor-specialties', doctorSpecialties);
        
        // 更新核心指标
        const totalDoctors = await doctorModel.countDocuments();
        pushDataUpdate('core-metrics', { totalDoctors });
      }
    });

    // 监听医院变化
    hospitalModel.watch().on('change', async (change) => {
      console.log('医院数据变化:', change.operationType);
      
      if (['insert', 'update', 'delete'].includes(change.operationType)) {
        // 重新获取医院分布数据
        const hospitalDistribution = await hospitalModel.aggregate([
          {
            $group: {
              _id: {
                // 使用省份作为主要分组键，与前端逻辑保持一致
                province: { $ifNull: ['$province', '$city'] }
              },
              count: { $sum: 1 },
              hospitals: { 
                $push: { 
                  name: '$name', 
                  rating: '$rating',
                  location: '$location',
                  category: '$category',
                  isHot: '$isHot',
                  services: '$services',
                  reviews: '$reviews',
                  doctors: '$doctors'
                } 
              },
              avgRating: { $avg: '$rating' },
              // 保存第一个城市的名称作为city字段
              firstCity: { $first: '$city' }
            }
          },
          { $sort: { count: -1 } }
        ]).then(distribution => distribution.map(item => ({
          name: item._id.province || '未知省份',
          city: item.firstCity || item._id.province || '未知城市',
          value: item.count,
          hospitals: item.hospitals,
          avgRating: Math.round(item.avgRating * 10) / 10
        })));
        
        pushDataUpdate('hospital-distribution', hospitalDistribution);
        
        // 更新核心指标
        const totalHospitals = await hospitalModel.countDocuments();
        pushDataUpdate('core-metrics', { totalHospitals });
      }
    });

    // 监听用户变化
    userModel.watch().on('change', async (change) => {
      console.log('用户数据变化:', change.operationType);
      
      if (['insert', 'update', 'delete'].includes(change.operationType)) {
        // 更新核心指标
        const totalUsers = await userModel.countDocuments();
        pushDataUpdate('core-metrics', { totalUsers });
      }
    });

    console.log('数据变化监听器已设置');
  } catch (error) {
    console.error('设置数据变化监听器失败:', error);
  }
};

// 启动数据变化监听
setupDataChangeListeners();

// ========== 网络测试接口 ==========
// 测试前端服务连接
router.get('/dashboard/test-connection', async (req, res) => {
  try {
    const frontendUrl = req.query.frontendUrl || 'http://localhost:3005';
    console.log('测试连接:', frontendUrl);
    
    // 使用简单的HTTP请求测试连接
    const http = require('http');
    const url = require('url');
    
    const parsedUrl = url.parse(frontendUrl);
    const options = {
      hostname: parsedUrl.hostname,
      port: parsedUrl.port,
      path: parsedUrl.path || '/',
      method: 'GET',
      timeout: 5000
    };
    
    const request = http.request(options, (response) => {
      console.log(`连接测试成功: ${frontendUrl} - 状态码: ${response.statusCode}`);
      res.send({
        success: true,
        message: '前端服务连接正常',
        url: frontendUrl,
        statusCode: response.statusCode
      });
    });
    
    request.on('error', (error) => {
      console.error(`连接测试失败: ${frontendUrl} - ${error.message}`);
      res.status(500).send({
        success: false,
        message: '前端服务连接失败',
        url: frontendUrl,
        error: error.message
      });
    });
    
    request.on('timeout', () => {
      console.error(`连接测试超时: ${frontendUrl}`);
      request.destroy();
      res.status(500).send({
        success: false,
        message: '前端服务连接超时',
        url: frontendUrl
      });
    });
    
    request.end();
    
  } catch (error) {
    console.error('连接测试异常:', error);
    res.status(500).send({
      success: false,
      message: '连接测试异常',
      error: error.message
    });
  }
});

// ========== 健康检查接口 ==========
// 检查前端服务状态
router.get('/dashboard/health-check', async (req, res) => {
  const puppeteer = require('puppeteer');
  
  try {
    // 支持通过查询参数传递前端URL
    const frontendUrl = req.query.frontendUrl || process.env.FRONTEND_URL || 'http://localhost:3000';
    const dashboardUrl = frontendUrl.includes('/dashboard') ? frontendUrl : `${frontendUrl}/dashboard`;
    
    console.log('检查前端服务状态:', dashboardUrl);
    
    const browser = await puppeteer.launch({
      headless: true,
      args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    const page = await browser.newPage();
    
    try {
      const response = await page.goto(dashboardUrl, {
        waitUntil: 'domcontentloaded',
        timeout: 10000
      });
      
      await browser.close();
      
      if (response && response.ok()) {
        res.send({
          success: true,
          message: '前端服务运行正常',
          url: dashboardUrl,
          status: response.status()
        });
      } else {
        res.status(500).send({
          success: false,
          message: '前端服务响应异常',
          url: dashboardUrl,
          status: response ? response.status() : '无响应'
        });
      }
    } catch (error) {
      await browser.close();
      throw error;
    }
    
  } catch (error) {
    console.error('前端服务检查失败:', error);
    res.status(500).send({
      success: false,
      message: '前端服务不可用',
      error: error.message,
      suggestion: '请确保前端服务正在运行 (npm run dev)'
    });
  }
});

// ========== PDF导出接口 ==========
// 导出Dashboard为PDF
router.post('/dashboard/export-pdf', async (req, res) => {
  const puppeteer = require('puppeteer');
  
  try {
    console.log('开始导出PDF...');
    console.log('请求参数:', req.body);
    
    // 获取前端URL（优先使用前端传递的URL）
    let frontendUrl = req.body.frontendUrl || process.env.FRONTEND_URL || 'http://localhost:3000';
    
    // 如果是localhost，尝试替换为127.0.0.1（在某些环境下更可靠）
    if (frontendUrl.includes('localhost')) {
      frontendUrl = frontendUrl.replace('localhost', '127.0.0.1');
    }
    
    const dashboardUrl = frontendUrl;
    
    console.log('原始前端URL:', req.body.frontendUrl);
    console.log('使用的前端URL:', dashboardUrl);
    
    // 启动浏览器
    const browser = await puppeteer.launch({
      headless: true,
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
        '--disable-accelerated-2d-canvas',
        '--no-first-run',
        '--no-zygote',
        '--disable-gpu',
        '--disable-web-security',
        '--disable-features=VizDisplayCompositor'
      ]
    });
    
    const page = await browser.newPage();
    
    // 设置视口大小，匹配Dashboard设计尺寸
    await page.setViewport({ 
      width: 1920, 
      height: 1080,
      deviceScaleFactor: 2 // 提高清晰度
    });
    
    console.log('访问Dashboard页面:', dashboardUrl);
    
    // 检查前端服务是否可用
    let pageLoadSuccess = false;
    let lastError = null;
    
    // 尝试多种方式访问页面
    const urlsToTry = [
      dashboardUrl,
      dashboardUrl.replace('127.0.0.1', 'localhost'),
      dashboardUrl.replace('localhost', '127.0.0.1')
    ];
    
    for (const url of urlsToTry) {
      try {
        console.log(`尝试访问: ${url}`);
        const response = await page.goto(url, {
          waitUntil: 'domcontentloaded', // 降低等待要求
          timeout: 15000
        });
        
        if (response && response.ok()) {
          console.log(`前端页面加载成功: ${url}`);
          pageLoadSuccess = true;
          break;
        } else {
          console.log(`响应异常: ${response ? response.status() : '无响应'}`);
        }
      } catch (error) {
        console.log(`访问失败: ${url} - ${error.message}`);
        lastError = error;
        continue;
      }
    }
    
    if (!pageLoadSuccess) {
      await browser.close();
      throw new Error(`无法访问前端服务，尝试了多个URL: ${urlsToTry.join(', ')}。最后错误: ${lastError ? lastError.message : '未知错误'}`);
    }
    
    // 等待页面完全加载
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    // 等待数据加载完成
    try {
      await page.waitForSelector('.dashboard-container', { timeout: 10000 });
      console.log('Dashboard容器已加载');
    } catch (error) {
      console.log('等待Dashboard容器超时，继续执行');
    }
    
    // 等待图表和数据加载
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    // 生成PDF
    const pdf = await page.pdf({
      format: 'A4',
      landscape: true, // 横向
      printBackground: true, // 包含背景
      margin: {
        top: '10mm',
        right: '10mm',
        bottom: '10mm',
        left: '10mm'
      }
    });
    
    await browser.close();
    
    console.log('PDF生成成功');
    
    // 设置响应头
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename="dashboard-report.pdf"');
    res.setHeader('Content-Length', pdf.length);
    
    // 发送PDF
    res.send(pdf);
    
  } catch (error) {
    console.error('PDF导出失败:', error);
    
    res.status(500).send({
      success: false,
      message: 'PDF导出失败',
      error: error.message
    });
  }
});


// 获取所有数据 - 医生、医院、商品完整信息
router.get('/all-data', async (req, res) => {
  try {
    console.log('开始获取所有数据（医生、医院、商品）...')
    
    // 并行获取所有数据
    const [allHospitals, allDoctors, allProducts] = await Promise.all([
      // 获取所有医院数据
      hospitalModel.find()
        .select('name rating location city province category isHot viewCount products doctor')
        .sort({ rating: -1, isHot: -1 }),
      
      // 获取所有医生数据
      doctorModel.find()
        .select('name hospital specialties city province isHot viewCount category')
        .sort({ isHot: -1, viewCount: -1 }),
      
      // 获取所有商品数据
      productModel.find()
        .select('title price hospital viewCount hospitals')
        .sort({ viewCount: -1 })
    ])
    
    // 计算统计信息
    const statistics = {
      totalHospitals: allHospitals.length,
      totalDoctors: allDoctors.length,
      totalProducts: allProducts.length,
      provinces: [...new Set(allHospitals.map(h => h.province).filter(Boolean))],
      cities: [...new Set(allHospitals.map(h => h.city).filter(Boolean))],
      specialties: [...new Set(allDoctors.flatMap(d => d.specialties || []).filter(Boolean))]
    }
    
    const allData = {
      hospitals: allHospitals,
      doctors: allDoctors,
      products: allProducts,
      statistics,
      timestamp: new Date()
    }
    
    console.log('所有数据获取完成:', {
      医院数量: allHospitals.length,
      医生数量: allDoctors.length,
      商品数量: allProducts.length,
      省份数量: statistics.provinces.length,
      城市数量: statistics.cities.length,
      专业数量: statistics.specialties.length
    })
    
    res.send({
      success: true,
      data: allData
    })
  } catch (error) {
    console.error('获取所有数据失败:', error)
    res.status(500).send({
      success: false,
      message: '获取数据失败',
      error: error.message
    })
  }
})

// 获取省份完整数据 - 包含该省份的所有医院、医生、产品
router.get('/province-complete-data/:province', async (req, res) => {
  try {
    const { province } = req.params
    console.log(`开始获取${province}的完整数据...`)
    
    // 1. 获取该省份的所有医院
    const provinceHospitals = await hospitalModel.find({ province: province })
      .select('name rating location city province category isHot viewCount products doctor')
      .sort({ rating: -1, isHot: -1 })
    
    if (provinceHospitals.length === 0) {
      return res.send({
        success: true,
        data: {
          hasData: false,
          message: `${province}暂无相关数据`,
          province: province,
          hospitals: [],
          doctors: [],
          products: [],
          statistics: {
            totalHospitals: 0,
            totalDoctors: 0,
            totalProducts: 0,
            cities: [],
            specialties: []
          }
        }
      })
    }
    
    // 2. 获取该省份的所有医生（通过医院关联）
    const hospitalNames = provinceHospitals.map(h => h.name)
    const hospitalIds = provinceHospitals.map(h => h._id.toString())
    
    const provinceDoctors = await doctorModel.find({
      $or: [
        { hospital: { $in: hospitalNames } },
        { hospitalId: { $in: hospitalIds } },
        { province: province }
      ]
    })
      .select('name hospital hospitalId specialties city province isHot viewCount category avatar tag')
      .sort({ isHot: -1, viewCount: -1 })
    
    // 3. 获取该省份的所有产品（通过医院关联），只返回前10个
    const provinceProducts = await productModel.find({
      'hospitals.hospitalName': { $in: hospitalNames }
    })
      .select('title price hospital viewCount hospitals rating tags image category')
      .sort({ viewCount: -1 })
      .limit(10)
    
    // 4. 计算统计信息
    const cities = [...new Set(provinceHospitals.map(h => h.city).filter(Boolean))]
    const specialties = [...new Set(provinceDoctors.flatMap(d => d.specialties || []).filter(Boolean))]
    
    const statistics = {
      totalHospitals: provinceHospitals.length,
      totalDoctors: provinceDoctors.length,
      totalProducts: provinceProducts.length,
      cities: cities,
      specialties: specialties,
      avgHospitalRating: provinceHospitals.length > 0 ? 
        (provinceHospitals.reduce((sum, h) => sum + (h.rating || 0), 0) / provinceHospitals.length).toFixed(1) : 0
    }
    
    // 5. 生成医生专业分布数据
    const specialtyCount = {}
    provinceDoctors.forEach(doctor => {
      if (doctor.specialties && doctor.specialties.length > 0) {
        doctor.specialties.forEach(specialty => {
          specialtyCount[specialty] = (specialtyCount[specialty] || 0) + 1
        })
      } else {
        const specialty = doctor.category || '其他'
        specialtyCount[specialty] = (specialtyCount[specialty] || 0) + 1
      }
    })
    
    const doctorSpecialtyDistribution = Object.entries(specialtyCount).map(([specialty, count]) => ({
      specialty,
      count,
      percentage: provinceDoctors.length > 0 ? ((count / provinceDoctors.length) * 100).toFixed(1) : '0.0'
    })).sort((a, b) => b.count - a.count)
    
    // 6. 生成价格分析数据
    const priceRanges = [
      { name: '500-1000', min: 500, max: 1000, color: '#00ffff' },
      { name: '1000-2000', min: 1000, max: 2000, color: '#ff00ff' },
      { name: '2000-3000', min: 2000, max: 3000, color: '#ffff00' },
      { name: '3000-5000', min: 3000, max: 5000, color: '#00ff00' },
      { name: '5000+', min: 5000, max: Infinity, color: '#ff6600' }
    ]
    
    const priceAnalysis = priceRanges.map(range => {
      const count = provinceProducts.filter(p => p.price >= range.min && p.price < range.max).length
      return { name: range.name, value: count, color: range.color }
    })
    
    const provinceData = {
      hasData: true,
      province: province,
      hospitals: provinceHospitals,
      doctors: provinceDoctors,
      products: provinceProducts,
      doctorSpecialtyDistribution: doctorSpecialtyDistribution,
      priceAnalysis: priceAnalysis,
      statistics: statistics,
      timestamp: new Date()
    }
    
    console.log(`${province}完整数据获取完成:`, {
      医院数量: provinceHospitals.length,
      医生数量: provinceDoctors.length,
      产品数量: provinceProducts.length,
      城市数量: cities.length,
      专业数量: specialties.length
    })
    
    res.send({
      success: true,
      data: provinceData
    })
  } catch (error) {
    console.error(`获取${req.params.province}完整数据失败:`, error)
    res.status(500).send({
      success: false,
      message: '获取省份数据失败',
      error: error.message
    })
  }
})

// Socket.IO 双向通信 - 省份数据实时获取
function setupProvinceSocketIO(io) {
  if (!io) {
    console.log('⚠️ Socket.IO 未初始化，跳过省份数据实时通信设置')
    return
  }

  console.log('🚀 设置省份数据 Socket.IO 实时通信...')

  // 监听省份数据请求
  io.on('connection', (socket) => {
    console.log('📱 客户端连接:', socket.id)

    // 请求省份完整数据
    socket.on('request-province-data', async (data) => {
      try {
        const { province, userId } = data
        console.log(`📡 收到省份数据请求: ${province} (用户: ${userId})`)

        if (!province) {
          socket.emit('province-data-response', {
            success: false,
            message: '缺少省份参数'
          })
          return
        }

        // 1. 获取该省份的所有医院
        const provinceHospitals = await hospitalModel.find({ province: province })
          .select('name rating location city province category isHot viewCount products doctor')
          .sort({ rating: -1, isHot: -1 })

        if (provinceHospitals.length === 0) {
          socket.emit('province-data-response', {
            success: true,
            data: {
              hasData: false,
              message: `${province}暂无相关数据`,
              province: province,
              hospitals: [],
              doctors: [],
              products: [],
              statistics: {
                totalHospitals: 0,
                totalDoctors: 0,
                totalProducts: 0,
                cities: [],
                specialties: []
              }
            }
          })
          return
        }

        // 2. 获取该省份的所有医生（通过医院关联）
        const hospitalNames = provinceHospitals.map(h => h.name)
        const hospitalIds = provinceHospitals.map(h => h._id.toString())

        const provinceDoctors = await doctorModel.find({
          $or: [
            { hospital: { $in: hospitalNames } },
            { hospitalId: { $in: hospitalIds } },
            { province: province }
          ]
        })
          .select('name hospital hospitalId specialties city province isHot viewCount category avatar tag')
          .sort({ isHot: -1, viewCount: -1 })

        // 3. 获取该省份的所有产品（通过医院关联），只返回前10个
        const provinceProducts = await productModel.find({
          'hospitals.hospitalName': { $in: hospitalNames }
        })
          .select('title price hospital viewCount hospitals rating tags image category')
          .sort({ viewCount: -1 })
          .limit(10)

        // 4. 计算统计信息
        const cities = [...new Set(provinceHospitals.map(h => h.city).filter(Boolean))]
        const specialties = [...new Set(provinceDoctors.flatMap(d => d.specialties || []).filter(Boolean))]

        const statistics = {
          totalHospitals: provinceHospitals.length,
          totalDoctors: provinceDoctors.length,
          totalProducts: provinceProducts.length,
          cities: cities,
          specialties: specialties,
          avgHospitalRating: provinceHospitals.length > 0 ? 
            (provinceHospitals.reduce((sum, h) => sum + (h.rating || 0), 0) / provinceHospitals.length).toFixed(1) : 0
        }

        // 5. 生成医生专业分布数据
        const specialtyCount = {}
        provinceDoctors.forEach(doctor => {
          if (doctor.specialties && doctor.specialties.length > 0) {
            doctor.specialties.forEach(specialty => {
              specialtyCount[specialty] = (specialtyCount[specialty] || 0) + 1
            })
          } else {
            const specialty = doctor.category || '其他'
            specialtyCount[specialty] = (specialtyCount[specialty] || 0) + 1
          }
        })

        // 只显示前6个主要专业，其他合并为"其他"
        const sortedSpecialties = Object.entries(specialtyCount)
          .map(([specialty, count]) => ({
            specialty,
            count,
            percentage: provinceDoctors.length > 0 ? ((count / provinceDoctors.length) * 100).toFixed(1) : '0.0'
          }))
          .sort((a, b) => b.count - a.count)
        
        const topSpecialties = sortedSpecialties.slice(0, 6)
        const otherSpecialties = sortedSpecialties.slice(6)
        
        // 计算"其他"的总数
        const otherCount = otherSpecialties.reduce((sum, item) => sum + item.count, 0)
        const otherPercentage = provinceDoctors.length > 0 ? ((otherCount / provinceDoctors.length) * 100).toFixed(1) : '0.0'
        
        const doctorSpecialtyDistribution = [
          ...topSpecialties,
          ...(otherCount > 0 ? [{
            specialty: '其他',
            count: otherCount,
            percentage: otherPercentage
          }] : [])
        ]

        // 6. 生成价格分析数据
        const priceRanges = [
          { name: '500-1000', min: 500, max: 1000, color: '#00ffff' },
          { name: '1000-2000', min: 1000, max: 2000, color: '#ff00ff' },
          { name: '2000-3000', min: 2000, max: 3000, color: '#ffff00' },
          { name: '3000-5000', min: 3000, max: 5000, color: '#00ff00' },
          { name: '5000+', min: 5000, max: Infinity, color: '#ff6600' }
        ]

        const priceAnalysis = priceRanges.map(range => {
          const count = provinceProducts.filter(p => p.price >= range.min && p.price < range.max).length
          return { name: range.name, value: count, color: range.color }
        })

        const provinceData = {
          hasData: true,
          province: province,
          hospitals: provinceHospitals,
          doctors: provinceDoctors,
          products: provinceProducts,
          doctorSpecialtyDistribution: doctorSpecialtyDistribution,
          priceAnalysis: priceAnalysis,
          statistics: statistics,
          timestamp: new Date()
        }

        console.log(`📤 发送${province}省份数据:`, {
          医院数量: provinceHospitals.length,
          医生数量: provinceDoctors.length,
          产品数量: provinceProducts.length
        })

        // 发送省份数据响应
        socket.emit('province-data-response', {
          success: true,
          data: provinceData
        })

      } catch (error) {
        console.error('❌ 获取省份数据失败:', error)
        socket.emit('province-data-response', {
          success: false,
          message: '获取省份数据失败',
          error: error.message
        })
      }
    })

    // 请求所有数据
    socket.on('request-all-data', async (data) => {
      try {
        const { userId } = data
        console.log(`📡 收到所有数据请求 (用户: ${userId})`)

        // 并行获取所有数据
        const [allHospitals, allDoctors, allProducts] = await Promise.all([
          // 获取所有医院数据
          hospitalModel.find()
            .select('name rating location city province category isHot viewCount products doctor')
            .sort({ rating: -1, isHot: -1 }),
          
          // 获取所有医生数据
          doctorModel.find()
            .select('name hospital specialties city province isHot viewCount category')
            .sort({ isHot: -1, viewCount: -1 }),
          
          // 获取所有商品数据
          productModel.find()
            .select('title price hospital viewCount hospitals')
            .sort({ viewCount: -1 })
        ])

        // 计算统计信息
        const statistics = {
          totalHospitals: allHospitals.length,
          totalDoctors: allDoctors.length,
          totalProducts: allProducts.length,
          provinces: [...new Set(allHospitals.map(h => h.province).filter(Boolean))],
          cities: [...new Set(allHospitals.map(h => h.city).filter(Boolean))],
          specialties: [...new Set(allDoctors.flatMap(d => d.specialties || []).filter(Boolean))]
        }

        const allData = {
          hospitals: allHospitals,
          doctors: allDoctors,
          products: allProducts,
          statistics,
          timestamp: new Date()
        }

        console.log('📤 发送所有数据:', {
          医院数量: allHospitals.length,
          医生数量: allDoctors.length,
          商品数量: allProducts.length,
          省份数量: statistics.provinces.length
        })

        // 发送所有数据响应
        socket.emit('all-data-response', {
          success: true,
          data: allData
        })

      } catch (error) {
        console.error('❌ 获取所有数据失败:', error)
        socket.emit('all-data-response', {
          success: false,
          message: '获取所有数据失败',
          error: error.message
        })
      }
    })

    // 加入仪表板更新房间
    socket.on('join-dashboard-updates', (data) => {
      try {
        const { userId } = data
        if (userId) {
          socket.join('dashboard:updates')
          console.log(`📱 用户 ${userId} 加入仪表板更新房间`)
        }
      } catch (error) {
        console.error('❌ 加入仪表板更新房间失败:', error)
      }
    })

    // 离开仪表板更新房间
    socket.on('leave-dashboard-updates', (data) => {
      try {
        const { userId } = data
        if (userId) {
          socket.leave('dashboard:updates')
          console.log(`📱 用户 ${userId} 离开仪表板更新房间`)
        }
      } catch (error) {
        console.error('❌ 离开仪表板更新房间失败:', error)
      }
    })

    // 断开连接
    socket.on('disconnect', () => {
      console.log('📱 客户端断开连接:', socket.id)
    })
  })

  console.log('✅ 省份数据 Socket.IO 实时通信设置完成')
}

// 导出路由和Socket.IO设置函数
module.exports = {
  router,
  setupProvinceSocketIO
};
